package com.cms.common.kit;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.cms.model.Category;
import com.cms.model.Res;


public class TreeBuilder {

	
	@SuppressWarnings("unchecked")
	public static List<Tree> buildListToTree(List<Tree> dirs) {
        List<Tree> roots = findRoots(dirs);
        List<Tree> notRoots = (List<Tree>) CollectionUtils.subtract(dirs, roots);
        for (Tree root : roots) {
            root.setChildren(findChildren(root, notRoots));
        }
        return roots;
    }

	@SuppressWarnings("unchecked")
	public static List<Tree> buildResToTree(List<Res> dirs) {
		List<Tree> dirs_tree = transferRes(dirs);
        return buildListToTree(dirs_tree);
    }
	
	@SuppressWarnings("unchecked")
	public static List<Tree> buildCateToTree(List<Category> dirs) {
		List<Tree> dirs_tree = transferCate(dirs);
        return buildListToTree(dirs_tree);
    }
	
	
    private static List<Tree> findRoots(List<Tree> allTrees) {
        List<Tree> roots = new ArrayList<Tree>();
        for (Tree tree : allTrees) {
           if(tree.getpId()==0)roots.add(tree);
        }
        return roots;
    }

    @SuppressWarnings("unchecked")
	private static List<Tree> findChildren(Tree root, List<Tree> allTrees) {
        List<Tree> children = new ArrayList<Tree>();
        for (Tree comparedOne : allTrees) {
            if (comparedOne.getpId()==root.getId()) {
                children.add(comparedOne);
            }
        }
        List<Tree> notChildren = (List<Tree>) CollectionUtils.subtract(allTrees, children);
        List<Tree> tmpChildren=null;
        for (Tree child : children) {
        	tmpChildren = findChildren(child, notChildren);
            child.setChildren(tmpChildren);
        }
        return children;
    }
    
    public static List<Tree> transferRes(List<Res> resList){
    	List<Tree> t_list=new ArrayList<>();
    	Tree t=null;
    	for (Res res : resList) {
			t=new Tree();
			t.setId(res.getInt("id"));
			t.setpId(res.getInt("pId"));
			t.setText(res.getStr("text"));
			t.setUrl(res.getStr("url"));
			t.setType(res.getInt("type"));
			t_list.add(t);
		}
    	return t_list;
    }
    
    public static List<Tree> transferCate(List<Category> resList){
    	List<Tree> t_list=new ArrayList<>();
    	Tree t=null;
    	for (Category res : resList) {
			t=new Tree();
			t.setId(res.getInt("id"));
			t.setpId(res.getInt("pid"));
			t.setText(res.getStr("name"));
			t.setUrl(res.getStr("url"));
			t_list.add(t);
		}
    	return t_list;
    }
    
   
}